package fi.iki.joker.mobilogger;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import android.R;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import fi.iki.joker.mobilogger.db.BlogEntryBean;
import fi.iki.joker.mobilogger.db.DBConstants;
import fi.iki.joker.mobilogger.db.DBUtil;
import fi.iki.joker.mobilogger.db.MemoBean;
import fi.iki.joker.mobilogger.util.AlertUtil;

/**
 * The editor for memos. This can take in an intent to edit a memo or create a new memo if there's no
 * intent to create new one.
 * @author juhak
 *
 */

public class MemoEditor extends Activity {
	
    private static final String TAG = "MemoEditor";

    private static final int NOTE_INDEX = 1;
    private static final int TITLE_INDEX = 2;
    private static final int MODIFIED_INDEX = 3;


    // This is our state data that is stored when freezing.
    private static final String ORIGINAL_CONTENT = "origContent";

    // Identifiers for our menu items.
    private static final int REVERT_ID = Menu.FIRST;
    private static final int DISCARD_ID = Menu.FIRST + 1;
    private static final int DELETE_ID = Menu.FIRST + 2;

    // The different distinct states the activity can be run in.
    private static final int STATE_EDIT = 0;
    private static final int STATE_INSERT = 1;
    private static final int STATE_DELETE = 2;

    private int mState;
    private boolean mNoteOnly = false;
    private Uri mURI;
    private Cursor mCursor;
    private EditText mText;
    private EditText mTitleText;
    private String mOriginalContent;
    private MemoBean mBean;
    private int currentPromoteId;
    private DialogInterface promoteDialog = null;
    
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(fi.iki.joker.mobilogger.R.layout.memoeditor);
        mBean = new MemoBean();
        mText = (EditText) findViewById(fi.iki.joker.mobilogger.R.id.memo);
        mTitleText = (EditText) findViewById(fi.iki.joker.mobilogger.R.id.memotitle);
        final Intent intent = getIntent();
        final String type = intent.resolveType(this);
        //set the memo title to the default:
        Date d = new Date(System.currentTimeMillis());
		SimpleDateFormat df = new SimpleDateFormat(DBConstants.DB_DATE_FORMAT);
		String memotitle = "Memo @ "+df.format(d);
		String memocontent = "";
        if(intent.getAction().equals(Intent.ACTION_INSERT)) {
        	mState = STATE_INSERT;
        	setResult(RESULT_OK, new Intent("temp"));
        } else if (intent.getAction().equals(Intent.ACTION_DELETE)) {
        	mState = STATE_DELETE;
        } else if (intent.getAction().equals(Intent.ACTION_EDIT)) {
        	mState = STATE_EDIT;
        	mURI = intent.getData();
        	int noteid = -1;
        	String id = mURI.getPath();
        	String temp = null;
        	if(id != null) {
        		try {
        			temp = id.substring(id.lastIndexOf('/')+1);
        			noteid = Integer.parseInt(temp);
        		} catch (NumberFormatException ne) {
        			Log.e(TAG, "Unable to parse the Intent path id ("+temp+") into an integer!");
        		}
        	}
        	if(noteid > 0) {
        		DBUtil conn = new DBUtil();
        		Log.d(TAG, "DB ready, fetching memo");
    	        mBean = conn.getMemo(this,noteid);
        		memotitle = mBean.getTitle();
        		memocontent = mBean.getContents();
        	}
        } else {
        	Log.e(TAG, "Unknown action, exiting");
        	finish();
        	return;
        }
		mTitleText.setText(memotitle);
		mText.setText(memocontent);
	}
	
	public static class MemoText extends EditText {
        private Rect mRect;
        private Paint mPaint;

        // we need this constructor for ViewInflate
        public MemoText(Context context, AttributeSet attrs) {
            super(context, attrs);

            mRect = new Rect();
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(0xFF0000FF);
        }

        @Override
        protected void onDraw(Canvas canvas) {

            int count = getLineCount();
            Rect r = mRect;
            Paint paint = mPaint;

            for (int i = 0; i < count; i++) {
                int baseline = getLineBounds(i, r);

                canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1,
                                paint);
            }

            super.onDraw(canvas);
        }
    }
	
	public static class TitleText extends EditText {
        private Rect mRect;
        private Paint mPaint;

        // we need this constructor for ViewInflate
        public TitleText(Context context, AttributeSet attrs) {
            super(context, attrs);

            mRect = new Rect();
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(0xFF0000FF);
        }

        @Override
        protected void onDraw(Canvas canvas) {

            int count = getLineCount();
            Rect r = mRect;
            Paint paint = mPaint;

            for (int i = 0; i < count; i++) {
                int baseline = getLineBounds(i, r);

                canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1,
                                paint);
            }

            super.onDraw(canvas);
        }
    }
	
	@Override
    public boolean onCreateOptionsMenu (Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, Menu.FIRST,  Menu.NONE,fi.iki.joker.mobilogger.R.string.memoeditor_save_option);
		menu.add(0, 3,  Menu.NONE,fi.iki.joker.mobilogger.R.string.memoeditor_promote_option);
		menu.add(0, 2,  Menu.NONE,fi.iki.joker.mobilogger.R.string.memoeditor_discard_option);
		return result; 
	}
	
	@Override
	
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemid = item.getItemId();
		switch(itemid) {
		case Menu.FIRST :
			Editable e = (Editable)this.mText.getText();
			Date d = new Date(System.currentTimeMillis());
			mBean.setContents(e.toString());
			mBean.setCreated(d);
			mTitleText = (EditText) findViewById(fi.iki.joker.mobilogger.R.id.memotitle);
			mBean.setTitle((mTitleText.getText()).toString());
			DBUtil conn = new DBUtil();
			if(mState == STATE_INSERT) { 
	        	conn.insert(this,mBean);
	        	//TODO: This dialog would not finish properly.
	        	//AlertUtil.showAlert(this,"Saved","Your memo was saved successfully.");
	        	this.finish();
	        } else if(mState == STATE_EDIT) {
	        	//TODO: This dialog would not finish properly.
	        	//AlertUtil.showAlert(this,"Updated","Your memo was updated successfully.");
	        	conn.update(this,mBean);
	        	this.finish();
	        }
			break;
		case 3 : 
			Editable content = (Editable)this.mText.getText();
			EditText title = (EditText)findViewById(fi.iki.joker.mobilogger.R.id.memotitle);
			if(content != null && content.length() == 0) {
				AlertUtil.showAlert(this,"Promote memo","In order to promote this memo to a blog entry, you need to create some content for it.");
				return super.onOptionsItemSelected(item);
			}
			if(title != null && title.length() == 0) {
				AlertUtil.showAlert(this,"Promote memo","In order to promote this memo to blog entry, it needs to have a title.");
				return super.onOptionsItemSelected(item);
			}
			//the memo has some "sensible" content. Let's create a blogentry bean based on that.
			BlogEntryBean beb = new BlogEntryBean();
			beb.setCreated(new Date(System.currentTimeMillis()));
			beb.setBlogEntry(content);
			beb.setTitle(title.getText().toString());
			Log.d(TAG,"Promoting memo to a blog entry (entry, title) "+content+","+title.getText().toString());
			DBUtil conn2 = new DBUtil();
			int bebNum = (int)conn2.insertAndReturnRow(this,beb);
			if(bebNum > 0) {
				currentPromoteId = bebNum;
			//needs thought	promoteDialog = AlertUtil.showAlert(this,"Promote memo","A copy of this memo has been saved as blog entry. Do you want to open it now in blog entry editor?", "Yes", yesOpenClickListener, "No", noOpenClickListener, false, null);
			} else {
				Log.e(TAG, "Failed to insert the BlogEntryBean to db!");
				AlertUtil.showAlert(this,"Promote memo","Failed to promote a memo to a blog entry, database insert failed!");
				return super.onOptionsItemSelected(item);
			}
			break;
		case 2 :
			this.finish();
			break;
		default:
			//should not happen
			Log.e(TAG, "Unidentified option item id...");
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	OnClickListener yesOpenClickListener = new OnClickListener() {
	    public void onClick(DialogInterface df, int item) {
	        promoteDialog.dismiss();
	    	editEntry(currentPromoteId);
		}	
	};
	
	OnClickListener noOpenClickListener = new OnClickListener() {
		public void onClick(DialogInterface df, int item) {
			promoteDialog.dismiss();
		}
	};
	
	private void editEntry(int entryId) {
    	Intent intent = new Intent();
		intent.setClass(this, BlogEntryEditor.class);
		intent.setAction(Intent.ACTION_EDIT);
		String URIStr = "content://fi.iki.joker.mobilogger/blogentry/"+entryId;
		intent.setData(Uri.parse(URIStr));
		this.startActivity(intent);
		this.finish();
    }
}
